//
//  lxAppDelegate.m
//  luodansc
//
//  Created by 倫 星 on 12/05/21.
//  Copyright (c) 2012年 方正株式会社. All rights reserved.
//

#import "lxAppDelegate.h"

#import "lxRootViewController.h"
#import "lxLoginViewController.h"
#import "lxShopViewController.h"
#import "lxSetUpViewController.h"
#import <AudioToolbox/AudioToolbox.h>

@implementation lxAppDelegate

@synthesize window = _window;
@synthesize tabBar = _tabBar;

- (void)dealloc
{
    [_window release];
    [_tabBar release];
    [super dealloc];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{    
    //揺る揺る
    application.applicationSupportsShakeToEdit = YES;
    _isDeviceTokenRequest = NO;
    [self appInit];
    
    CGRect main_ret = [[UIScreen mainScreen] bounds];
    self.window = [[[UIWindow alloc] initWithFrame:main_ret] autorelease];
    self.window.backgroundColor = [UIColor whiteColor];
    // Override point for customization after application launch.
    
    _tabBar = [[UITabBarController alloc]init];
    lxRootViewController *lxRVC = [[lxRootViewController alloc] init];
    [lxRVC reFlash];
    [lxRVC setHorizMenuSelectedInit];
    UINavigationController *rnav = [[UINavigationController alloc] initWithRootViewController:lxRVC];
    [lxRVC release];
    
//    lxShopViewController *lxShVC = [[lxShopViewController alloc] init];
//    UINavigationController *shnav = [[UINavigationController alloc] initWithRootViewController:lxShVC];
//    [lxShVC release];
  
    lxSetUpViewController *lxSVC = [[lxSetUpViewController alloc] init];
    UINavigationController *snav = [[UINavigationController alloc] initWithRootViewController:lxSVC];
    [lxSVC release];
    
    _tabBar.viewControllers = [NSArray arrayWithObjects:rnav, snav, nil];
    [rnav release];
//    [shnav release];
    [snav release];

    [self.window addSubview:_tabBar.view];
    self.window.rootViewController = _tabBar;
    
    [self.window makeKeyAndVisible];
    
    //向微信注册
    [WXApi registerApp:@"wx49d3c2420001a276"];
    
//#if !TARGET_IPHONE_SIMULATOR
    // Let the device know we want to receive push notifications
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
//#endif
    application.applicationIconBadgeNumber = 0;
    [self clearDeviceBadgeRequest];
    if (nil != launchOptions) {
        NSDictionary *userInfo = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
        if (nil != userInfo) {
            [self application:application didReceiveRemoteNotification:userInfo];
        }
    }
    
    return YES;
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    return  [WXApi handleOpenURL:url delegate:self];
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    return  [WXApi handleOpenURL:url delegate:self];
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    NSString *strDeviceToken = [[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
    strDeviceToken = [strDeviceToken stringByReplacingOccurrencesOfString:@" " withString:@""];

    NSLog(@"My token is: %@", strDeviceToken);
    
    lxAPPContainer *appContainer = [lxAPPContainer sharedLxAPPContainer];
    [appContainer.userDefaults setObject:strDeviceToken forKey:UserDefaultDeviceTokenKey];
    [self sendDeviceTokenRequest];
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"Failed to get token, error: %@", error);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
/*
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    UILocalNotification *notification = [[UILocalNotification alloc] init];
    [notification setFireDate:[NSDate date]];
    [notification setTimeZone:[NSTimeZone defaultTimeZone]];
    [notification setAlertBody:[[userInfo objectForKey:@"aps"] objectForKey:@"alert"]];
    [notification setUserInfo:userInfo];
    [[UIApplication sharedApplication] presentLocalNotificationNow:notification];
*/
    

    //收到消息自定义事件
    if ([[userInfo objectForKey:@"aps"] objectForKey:@"alert"] != nil) {
        UIApplicationState state = [application applicationState];
        if (state == UIApplicationStateActive){
            int badge = 0;
            if (nil != [[userInfo objectForKey:@"aps"] objectForKey:@"badge"]) {
                badge = [[[userInfo objectForKey:@"aps"] objectForKey:@"badge"] integerValue];
            }
            application.applicationIconBadgeNumber = badge;
        }
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"notice", nil)
                            message:[[userInfo objectForKey:@"aps"] objectForKey:@"alert"]
                            delegate:self
                            cancelButtonTitle:NSLocalizedString(@"ok", nil)
                            otherButtonTitles:nil];
        [alert show];
        [alert release];
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    //当没登录(或者程序没打开)的时候 在点登录后 初始化tabar 定位到alert page
    //清除掉icon上的数字
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    [self clearDeviceBadgeRequest];
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    application.applicationIconBadgeNumber = 0;
    [self clearDeviceBadgeRequest];
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

-(void) appInit
{
	lxDBAccessor* dbAccessor = [lxDBAccessor sharedLxDBAccessor];
    lxAPPContainer *appContainer = [lxAPPContainer sharedLxAPPContainer];

	NSFileManager* fileManger = [NSFileManager defaultManager];
	NSString* dbFilePath = [[lxPathUtility db3Path] stringByAppendingPathComponent:DBFileName];
	if ([fileManger fileExistsAtPath:dbFilePath])
	{
		//检索版本信息
        lxUserInfoEntity *userInfo = (lxUserInfoEntity *)[dbAccessor getUserInfo];
        lxAppInfoEntity *appInfo = (lxAppInfoEntity *)[dbAccessor getAppInfo];
        
        if (nil != userInfo) {
            userInfo.user_name = [lxStringUtility stringTrim:userInfo.user_name];
            if (NO == [lxStringUtility isNil:userInfo.user_name]) {
                userInfo.password = [lxStringUtility stringTrim:userInfo.password];
                if (NO == [lxStringUtility isNil:userInfo.password]) {
                    if (YES == [appContainer isExistNet]) {
                        [appContainer setUserInfoEntity:userInfo];
                        [self sendRequest:userInfo.user_name password:userInfo.password isStartAsynchronous:YES];
                    }
                }
            }
        }

        [appContainer setAppInfoEntity:appInfo];
	}
	NSString* version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
	//与当前版本号不同
	if (![version isEqualToString:[appContainer getAppInfoEntity].version])
	{
        lxAppInfoEntity *appInfo = [[lxAppInfoEntity alloc] init];
        appInfo.name = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleDisplayName"];
        appInfo.version = version;
        [appContainer setAppInfoEntity:appInfo];
		//初次启动
		//清空原有数据
        if (![fileManger fileExistsAtPath:dbFilePath]) {
            [fileManger removeItemAtPath:DOCUMENTS_DB error:NULL];
            [fileManger createDirectoryAtPath:DOCUMENTS_DB
                  withIntermediateDirectories:YES
                                   attributes:nil
                                        error:NULL];
            [fileManger removeItemAtPath:DOCUMENTS_COVER error:NULL];
            [fileManger createDirectoryAtPath:DOCUMENTS_COVER
                  withIntermediateDirectories:YES
                                   attributes:nil
                                        error:NULL];
            [fileManger removeItemAtPath:[NSHomeDirectory() stringByAppendingPathComponent:@"tmp"] error:NULL];
        }
        
		//存入版本信息
		[dbAccessor setAppInfo:[appContainer getAppInfoEntity]];
	}
}

#pragma mark -
#pragma mark EGORefreshTableHeaderDelegate Methods

- (ASIHTTPRequest *)sendRequest:(NSString *)user_name password:(NSString *)password isStartAsynchronous:(BOOL)isStartAsynchronous {
    lxAPPContainer *appContainer = [lxAPPContainer sharedLxAPPContainer];

    NSString *strDeviceToken = [appContainer.userDefaults objectForKey:UserDefaultDeviceTokenKey];
    int user_id = [appContainer getUserInfoEntity].user_id;
    
    if (YES == [lxStringUtility isNil:strDeviceToken]) {
        strDeviceToken = @"";
    }
    
    NSString *str_url = [NSString stringWithFormat:@"%@%@?user_name=%@&password=%@&device_token=%@&user_id=%d", service_url, getUserInfoServlet, user_name, password, strDeviceToken, user_id];
    NSURL *url = [NSURL URLWithString:str_url];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    [request setDelegate:self];
    
    if (YES == isStartAsynchronous) {
        [request startAsynchronous];
    } else {
        [request startSynchronous];
    }
    return request;
}

- (ASIHTTPRequest *)sendDeviceTokenRequest {
    lxAPPContainer *appContainer = [lxAPPContainer sharedLxAPPContainer];
    NSString *strDeviceToken = [appContainer.userDefaults objectForKey:UserDefaultDeviceTokenKey];

    if (YES == [lxStringUtility isNil:strDeviceToken]) {
        return nil;
    }

    int user_id = [appContainer getUserInfoEntity].user_id;
    NSLog(@"user_id is: %d", user_id);
    NSString *str_url = [NSString stringWithFormat:@"%@%@?device_token=%@&user_id=%d", service_url, setApnsInfoServlet, strDeviceToken, user_id];
    NSLog(@"lun sendDeviceTokenRequest str_url is: %@", str_url);

    NSURL *url = [NSURL URLWithString:str_url];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    [request setDelegate:self];
    [request startAsynchronous];
    _isDeviceTokenRequest = YES;
    return request;
}

- (ASIHTTPRequest *)clearDeviceBadgeRequest {
    lxAPPContainer *appContainer = [lxAPPContainer sharedLxAPPContainer];
    NSString *strDeviceToken = [appContainer.userDefaults objectForKey:UserDefaultDeviceTokenKey];
    
    if (YES == [lxStringUtility isNil:strDeviceToken]) {
        return nil;
    }

    NSString *str_url = [NSString stringWithFormat:@"%@%@?device_token=%@", service_url, clearDeviceBadgeServlet, strDeviceToken];
    NSLog(@"lun sendDeviceTokenRequest str_url is: %@", str_url);
    
    NSURL *url = [NSURL URLWithString:str_url];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    [request setDelegate:self];
    [request startAsynchronous];
    return request;
}

- (BOOL)getResponse:(ASIHTTPRequest *)request {
    NSString *responseString = [request responseString];
    
    if (![responseString isKindOfClass:[NSString class]]) {
        NSLog(@"reponsedate is nil");
        return NO;
    }
    
    if ([lxStringUtility isNil:responseString]) {
        NSLog(@"reponsedate is nil");
        return NO;
    }
    
    NSData *reponsedata = [responseString dataUsingEncoding:NSUTF8StringEncoding];
    
    if (nil == reponsedata) {
        NSLog(@"reponsedate is nil");
        return NO;
    }
    
    if (![reponsedata isKindOfClass:[NSData class]]) {
        NSLog(@"reponsedate is nil");
        return NO;
    }
    
    __autoreleasing NSError *error = nil;
    
    NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:reponsedata options:kNilOptions error:&error];
    if (nil == dictionary) {
        NSLog(@"Response failed because:%@", [error localizedDescription]);
        return NO;
    }
    
    if (![dictionary isKindOfClass:[NSDictionary class]]) {
        NSLog(@"Response failed because:%@", [error localizedDescription]);
        return NO;
    }
    
    lxUserInfoEntity *userEntity = [[lxUserInfoEntity alloc] init];
    
    BOOL result = [userEntity setEntity:dictionary];
    if (YES == result) {
        lxAPPContainer *appContainer = [lxAPPContainer sharedLxAPPContainer];
        NSString *password = [appContainer getUserInfoEntity].password;
        userEntity.password = password;
        [appContainer setUserInfoEntity:userEntity];
    }
    
    return YES;
}

- (BOOL)getDeviceTokenResponse:(ASIHTTPRequest *)request {
    NSString *responseString = [request responseString];
    
    if (![responseString isKindOfClass:[NSString class]]) {
        NSLog(@"reponsedate is nil");
        return NO;
    }
    
    if ([lxStringUtility isNil:responseString]) {
        NSLog(@"reponsedate is nil");
        return NO;
    }
    
    return YES;
}

- (void)requestFinished:(ASIHTTPRequest *)request {
    if (NO == _isDeviceTokenRequest) {

        BOOL result = [self getResponse:request];
        if (NO == result) {
            return;
        }
        lxAPPContainer *appContainer = [lxAPPContainer sharedLxAPPContainer];
    
        if (YES == [lxStringUtility isNil:[appContainer getUserInfoEntity].user_name]) {
            return;
        }
    
        if (YES == [lxStringUtility isNil:[appContainer getUserInfoEntity].password]) {
            return;
        }
    
        lxDBAccessor* dbAccessor = [lxDBAccessor sharedLxDBAccessor];
        [dbAccessor setUserInfo:[appContainer getUserInfoEntity]];
    } else {
        BOOL result = [self getDeviceTokenResponse:request];
        if (NO == result) {
            _isDeviceTokenRequest = NO;
            return;
        }
    }
    
    _isDeviceTokenRequest = NO;
}

- (void)requestFailed:(ASIHTTPRequest *)request {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"error", nil)
                                                    message:NSLocalizedString(@"network_conn_failed", nil)
                                                   delegate:self
                                          cancelButtonTitle:NSLocalizedString(@"ok", nil)
                                          otherButtonTitles:nil];
    [alert show];
    [alert release];
    _isDeviceTokenRequest = NO;
}

-(void) onReq:(BaseReq*)req
{
    if([req isKindOfClass:[GetMessageFromWXReq class]])
    {
    }
    else if([req isKindOfClass:[ShowMessageFromWXReq class]])
    {
    }
    
}

-(void) onResp:(BaseResp*)resp
{
    if([resp isKindOfClass:[SendMessageToWXResp class]])
    {
        NSString *strTitle = [NSString stringWithFormat:@"发送结果"];
        NSString *strMsg = [NSString stringWithFormat:@"发送媒体消息结果:%d", resp.errCode];
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:strTitle message:strMsg delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
        [alert release];
    }
    else if([resp isKindOfClass:[SendAuthResp class]])
    {
        NSString *strTitle = [NSString stringWithFormat:@"Auth结果"];
        NSString *strMsg = [NSString stringWithFormat:@"Auth结果:%d", resp.errCode];
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:strTitle message:strMsg delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
        [alert release];
    }
}

@end
